package cn.amaake.magicplugin.rpc.controller;

import cn.amaake.magicplugin.rpc.model.RpcInfo;
import cn.amaake.magicplugin.rpc.model.RpcParamData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ssssssss.magicapi.core.config.MagicConfiguration;
import org.ssssssss.magicapi.core.config.WebSocketSessionManager;
import org.ssssssss.magicapi.core.logging.MagicLoggerContext;
import org.ssssssss.magicapi.core.model.DebugRequest;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.web.MagicController;
import org.ssssssss.magicapi.core.web.MagicExceptionHandler;
import org.ssssssss.magicapi.utils.ScriptManager;
import org.ssssssss.script.MagicScriptDebugContext;
import java.util.List;

public class MagicRpcController extends MagicController implements MagicExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(MagicRpcController.class);

    private ApplicationContext applicationContext;

    public MagicRpcController(MagicConfiguration configuration,ApplicationContext applicationContext) {
        super(configuration);
        this.applicationContext = applicationContext;
    }

    @PostMapping("/magicrpc/execute")
    @ResponseBody
    public JsonBean<Object> execute(String id, MagicHttpServletRequest request){
        RpcInfo entity = MagicConfiguration.getMagicResourceService().file(id);
        notNull(entity, FILE_NOT_FOUND);
        String script = entity.getScript();
        DebugRequest debugRequest = DebugRequest.create(request);
        MagicLoggerContext.SESSION.set(debugRequest.getRequestedClientId());
        String sessionAndScriptId = debugRequest.getRequestedClientId() + debugRequest.getRequestedScriptId();
        try {
            MagicScriptDebugContext magicScriptContext = debugRequest.createMagicScriptContext(configuration.getDebugTimeout());
            WebSocketSessionManager.addMagicScriptContext(sessionAndScriptId, magicScriptContext);
            magicScriptContext.setScriptName(MagicConfiguration.getMagicResourceService().getScriptName(entity));
            List<RpcParamData> rpcParamDataList = entity.getParamData();
            if (rpcParamDataList!=null && !rpcParamDataList.isEmpty()){
                for(RpcParamData rpcParamData : rpcParamDataList){
                    magicScriptContext.set(rpcParamData.getFieldName(),rpcParamData.getTestValue());
                }
            }
            JsonBean<Object> jsonBean = new JsonBean<>(ScriptManager.executeScript(script, magicScriptContext));
            logger.info("code:{}", jsonBean.getCode());
            logger.info("message:{}", jsonBean.getMessage());
            logger.info("data:{}", jsonBean.getData().toString());
            logger.info("timestamp:{}", jsonBean.getTimestamp());
            logger.info("executeTime:{}", jsonBean.getExecuteTime());
            return jsonBean;
        } finally {
            WebSocketSessionManager.removeMagicScriptContext(sessionAndScriptId);
            MagicLoggerContext.SESSION.remove();
        }
    }

//    @PostMapping("/rpcprovider/test")
//    public JsonBean<String> rpcprovidertest(@RequestBody Map<String,Object> map) {
//        JSONObject jsonObject = JSONUtil.parseObj(map.get("info"));
//        RpcProviderInfo rpcProviderInfo = JSONUtil.toBean(jsonObject, RpcProviderInfo.class);
//        RpcProviderInfo groupInfo = MagicConfiguration.getMagicResourceService().file(rpcProviderInfo.getGroupId());
//
//        ApplicationConfig applicationConfig = new ApplicationConfig();
//        applicationConfig.setName(applicationContext.getApplicationName());
//
//        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
//
//        RegistryConfig registryConfig = new RegistryConfig();
//        registryConfig.setAddress(rpcProviderInfo.getAddress());
//        if(rpcProviderInfo.isIsauth()){
//            registryConfig.setUsername(rpcProviderInfo.getUsername());
//            registryConfig.setPassword(rpcProviderInfo.getPassword());
//        }
//
//        referenceConfig.setInterface(groupInfo.getPath());
//        //referenceConfig.setVersion("1.0.0");
//        referenceConfig.setApplication(applicationConfig);
//        referenceConfig.setRegistry(registryConfig);
//        referenceConfig.setGeneric("true");
//        // do not wait for result, 'false' by default
//        //referenceConfig.setAsync(true);
//        referenceConfig.setTimeout(rpcProviderInfo.getTimeout());
//
//        try{
//            GenericService  genericService = referenceConfig.get();
//        } catch (Exception e) {
//            return new JsonBean<>(0,"验证失败！"+e.getMessage());
//        }
//        return new JsonBean<>("ok");
//    }
}